//
//  ZCSecureTools.m
//  leda
//
//  Created by cuibo on 16/4/3.
//  Copyright © 2016年 cuibo. All rights reserved.
//

#import "ZCSecureTools.h"
#import <CommonCrypto/CommonDigest.h>
#import "RSA.h"
//#import "SJOauthStore.h"
#import "GTMBase64.h"
#import "NSData+Base64.h"
#import "NSString+Base64.h"
#import "NSData+AES.h"
#import "NSData+CommonCrypto.h"

@implementation ZCSecureTools

////md5 32位 加密 （小写）
//+ (NSString *)md5:(NSString *)str
//{
//    const char *cStr = [str UTF8String];
//    unsigned char result[32];
//    CC_MD5( cStr, (unsigned int)strlen(cStr), result );
//    
//    return [NSString stringWithFormat:
//        @"%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x",
//        result[0],result[1],result[2],result[3],
//        result[4],result[5],result[6],result[7],
//        result[8],result[9],result[10],result[11],
//        result[12],result[13],result[14],result[15],
//        result[16], result[17],result[18], result[19],
//        result[20], result[21],result[22], result[23],
//        result[24], result[25],result[26], result[27],
//        result[28], result[29],result[30], result[31]];
//}

+ (NSString *)md5:(NSString *)str
 {
     const char *cStr = [str UTF8String];
     unsigned char result[16];
     CC_MD5( cStr, (unsigned int)strlen(cStr), result);
     return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                            result[0], result[1], result[2], result[3],
                            result[4], result[5], result[6], result[7],
                            result[8], result[9], result[10], result[11],
                            result[12], result[13], result[14], result[15]
   ];
}

//+ (NSString *)rsa:(NSString *)str
//{
////    return [RSA encryptString:str publicKey:[SJOAuthStore shared].RSApublicKey];
//}
//
//+ (NSString *)deRsa:(NSString *)str
//{
////    return [RSA decryptString:str publicKey:[SJOAuthStore shared].RSApublicKey];
//}

+ (NSString *)sha256:(NSString *)str
{
    const char *s = [str cStringUsingEncoding:NSASCIIStringEncoding];
    NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];
    
    uint8_t digest[CC_SHA256_DIGEST_LENGTH] = {0};
    CC_SHA256(keyData.bytes, (CC_LONG)keyData.length, digest);
    NSData *out = [NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
    NSString *hash = [out description];
    hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
    hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
    hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
    
    return hash;
}

#pragma mark - AES加密
//ECB,1
+ (NSString *)encrypt:(NSString *)message password:(NSString *)password {
//    NSData *encryptedData = [[message dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptedDataUsingKey:[[password dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash] error:nil];
    
    CCCryptorStatus status = kCCSuccess;
    NSData* result = [[message dataUsingEncoding:NSUTF8StringEncoding]
                      dataEncryptedUsingAlgorithm:kCCAlgorithmAES128
                      key:password
                      initializationVector:nil   // ECB加密不会用到iv
                      options:(kCCOptionPKCS7Padding|kCCOptionECBMode)
                      error:&status];
    
    NSString *base64EncodedString = [NSString base64StringFromData:result length:[result length]];
    return base64EncodedString;
}

+ (NSString *)decrypt:(NSString *)base64EncodedString password:(NSString *)password {
    NSData *encryptedData = [NSData base64DataFromString:base64EncodedString];
    NSData *decryptedData = [encryptedData decryptedAES256DataUsingKey:[[password dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash] error:nil];
    return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
}

//ECB,2
- (NSData *)encryptText:(NSString*)text key:(NSString *)key
{
    CCCryptorStatus status = kCCSuccess;
    NSData* result = [[text dataUsingEncoding:NSUTF8StringEncoding]
                      dataEncryptedUsingAlgorithm:kCCAlgorithmAES128
                      key:key
                      initializationVector:nil   // ECB加密不会用到iv
                      options:(kCCOptionPKCS7Padding|kCCOptionECBMode)
                      error:&status];
    if (status != kCCSuccess) {
        NSLog(@"加密失败:%d", status);
        return nil;
    }
    return result;
}
- (NSString *)decryptText:(NSData*)data key:(NSString *)key
{
    CCCryptorStatus status = kCCSuccess;
    NSData* result = [data decryptedDataUsingAlgorithm:kCCAlgorithmAES128
                                                   key:key
                                  initializationVector:nil   // ECB解密不会用到iv
                                               options:(kCCOptionPKCS7Padding|kCCOptionECBMode)
                                                 error:&status];
    if (status != kCCSuccess)
    {
        NSLog(@"加密失败:%d", status);
        return nil;
    }
    return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
}


//解密
+(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key
{

   // NSData *encryptedData = [NSData base64DataFromString:encryptText];
   NSData *encryptedData = [encryptText dataUsingEncoding:NSUTF8StringEncoding];
    CCCryptorStatus status = kCCSuccess;
    NSData* result = [encryptedData decryptedDataUsingAlgorithm:kCCAlgorithmAES128
                                                   key:key
                                  initializationVector:nil   // ECB解密不会用到iv
                                               options:(kCCOptionPKCS7Padding)
                                                 error:&status];
    if (status != kCCSuccess)
    {
        NSLog(@"加密失败:%d", status);
        return nil;
    }
    NSString *path = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    return path;
    
}
// 普通字符串转换为十六进
+ (NSString *)hexStringFromData:(NSData *)data {
    Byte *bytes = (Byte *)[data bytes];
    // 下面是Byte 转换为16进制。
    NSString *hexStr = @"";
    for(int i=0; i<[data length]; i++) {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i] & 0xff]; //16进制数
        newHexStr = [newHexStr uppercaseString];
          
        if([newHexStr length] == 1) {
            newHexStr = [NSString stringWithFormat:@"0%@",newHexStr];
        }
          
        hexStr = [hexStr stringByAppendingString:newHexStr];
          
    }
    return hexStr;
}

//十六进制转Data
//十六进制转Data
+ (NSData*)dataForHexString:(NSString*)hexString
{
    if (hexString == nil) {
        return nil;
    }
    const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];
    NSMutableData* data = [NSMutableData data];
    while (*ch) {
        if (*ch == ' ') {
            continue;
        }
        char byte = 0;
        if ('0' <= *ch && *ch <= '9') {
            byte = *ch - '0';
        }else if ('a' <= *ch && *ch <= 'f') {
            byte = *ch - 'a' + 10;
        }else if ('A' <= *ch && *ch <= 'F') {
            byte = *ch - 'A' + 10;
        }
        ch++;
        byte = byte << 4;
        if (*ch) {
            if ('0' <= *ch && *ch <= '9') {
                byte += *ch - '0';
            } else if ('a' <= *ch && *ch <= 'f') {
                byte += *ch - 'a' + 10;
            }else if('A' <= *ch && *ch <= 'F'){
                byte += *ch - 'A' + 10;
            }
            ch++;
        }
        [data appendBytes:&byte length:1];
    }
    return data;
}
//CBC
+(NSString*)encryptAESData:(NSString*)string app_key:(NSString*)key
{
    //将nsstring转化为nsdata
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    //使用密码对nsdata进行加密
    NSData *encryptedData = [data AES128EncryptWithKey:key gIv:nil];
    //返回进行base64进行转码的加密字符串
    return [self encodeBase64Data:encryptedData];
}
+(NSString*)decryptAESData:(NSString *)string  app_key:(NSString*)key
{
    //base64解密
    NSData *decodeBase64Data=[GTMBase64 decodeString:string];
    //使用密码对data进行解密
    NSData *decryData = [decodeBase64Data AES128DecryptWithKey:key gIv:nil];
    //将解了密码的nsdata转化为nsstring
    NSString *str = [[NSString alloc] initWithData:decryData encoding:NSUTF8StringEncoding];
    return str;
}

#pragma mark - base64

+ (NSString*)encodeBase64String:(NSString * )input {
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    data = [GTMBase64 encodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}

+ (NSString*)decodeBase64String:(NSString * )input {
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    data = [GTMBase64 decodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}

+ (NSString*)encodeBase64Data:(NSData *)data {
    data = [GTMBase64 encodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}

+ (NSString*)decodeBase64Data:(NSData *)data {
    data = [GTMBase64 decodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}

@end
